package com.auto.reg.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;

public class FileUtil {
	
	public static File getVerifyCodeImg(String prefix) {

		FileUtil.deleteDirectiory(RegConstant.IE_LOCAL_DIR);
		File localCache = new File(RegConstant.IE_LOCAL_DIR);
		localCache.mkdir();

		try {
			copyDirectiory(RegConstant.IE_CACHE_DIR, RegConstant.IE_LOCAL_DIR);

			List<File> results = new ArrayList<File> ();
			searchFile(localCache, prefix, results);
			if (results.size() != 0) {
			    if (results.size() == 1) {
			    	return results.get(0);
			    } else {
			    	File selectedFile = results.get(0);
			        for (int i=1; i<results.size(); i++) {
			        	if (results.get(i).lastModified() > selectedFile.lastModified()) {
			        		selectedFile = results.get(i);
			        	}
			        }
			        return selectedFile;
			    }
			} else {
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public static void deleteDirectiory(String absoluteFilePath) {

		File file = new File(absoluteFilePath);
		if (file.exists() && file.isDirectory()) {
			if (file.listFiles().length == 0) {
				file.delete();
			} else {
				for (File f:file.listFiles()) {
					if (f.isDirectory()) {
						deleteDirectiory(f.getAbsolutePath());
					} else {
						f.delete();
					}
				}
			}
		}
	}

	private static void searchFile(File baseDir, String key, List<File> results) {

		for(File file:baseDir.listFiles()) {
			if (file.isDirectory()) {
				searchFile(file, key, results);
			} else {
				if (file.getName().startsWith(key)) {
					results.add(file);
				}
			}
		}
	}

	public static void main(String[] args) throws Exception {

//		File file = new File("D:/test/");
//		if (!file.exists()) {
//			file.mkdir();
//		}
//		copyDirectiory(RegConstant.IE_CACHE_DIR, "D:/test/");
//		File f = getVerifyCodeImg("wr[");
//		System.out.println(f.getAbsolutePath());
		deleteDirectiory(RegConstant.IE_LOCAL_DIR);
	}

    public static void copyFile(File sourceFile, File targetFile) throws IOException {

        BufferedInputStream inBuff = null;
        BufferedOutputStream outBuff = null;
        try {
            inBuff = new BufferedInputStream(new FileInputStream(sourceFile));

            outBuff = new BufferedOutputStream(new FileOutputStream(targetFile));

            byte[] b = new byte[1024 * 5];
            int len;
            while ((len = inBuff.read(b)) != -1) {
                outBuff.write(b, 0, len);
            }
            outBuff.flush();
        } finally {
            if (inBuff != null)
                inBuff.close();
            if (outBuff != null)
                outBuff.close();
        }
    }

    public static void copyDirectiory(String sourceDir, String targetDir) throws IOException {

        (new File(targetDir)).mkdirs();
        File[] file = (new File(sourceDir)).listFiles();
        for (int i = 0; i < file.length; i++) {
            if (file[i].isFile()) {
                File sourceFile = file[i];
                File targetFile = new File(new File(targetDir).getAbsolutePath() + File.separator + file[i].getName());
                copyFile(sourceFile, targetFile);
            }
            if (file[i].isDirectory()) {
                String dir1 = sourceDir + "/" + file[i].getName();
                String dir2 = targetDir + "/" + file[i].getName();
                copyDirectiory(dir1, dir2);
            }
        }
    }

    public static void copyFile(File srcFileName, File destFileName, String srcCoding, String destCoding) throws IOException {

        BufferedReader br = null;
        BufferedWriter bw = null;
        try {
            br = new BufferedReader(new InputStreamReader(new FileInputStream(srcFileName), srcCoding));
            bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(destFileName), destCoding));
            char[] cbuf = new char[1024 * 5];
            int len = cbuf.length;
            int off = 0;
            int ret = 0;
            while ((ret = br.read(cbuf, off, len)) > 0) {
                off += ret;
                len -= ret;
            }
            bw.write(cbuf, 0, off);
            bw.flush();
        } finally {
            if (br != null)
                br.close();
            if (bw != null)
                bw.close();
        }
    }

}
